package com.example.yijian.edit.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.example.yijian.MSApplication;
import com.example.yijian.R;
import com.example.yijian.edit.background.SpaceItemDecoration;
import com.example.yijian.edit.watermarker.FileUtil;
import com.example.yijian.edit.watermarker.WaterMarkCacheData;
import com.example.yijian.edit.watermarker.WaterMarkConstant;
import com.example.yijian.edit.watermarker.WaterMarkItemData;
import com.example.yijian.utils.PathUtils;
import com.example.yijian.utils.ScreenUtils;
import com.example.yijian.utils.SystemUtils;
import com.google.gson.Gson;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static android.widget.LinearLayout.HORIZONTAL;
import static com.example.yijian.edit.watermarker.WaterMarkItemData.ASSETSPICTURE;
import static com.example.yijian.edit.watermarker.WaterMarkItemData.SDCARDPICTURE;

public class WaterMarkView extends RelativeLayout {
    private Context mContext;
    private View rootView;
    private RecyclerView recyclerWatermark;
    private ImageView ivFinish;

    private int type = WaterMarkConstant.WATERMARKTYPE_STATIC;
    private HomeAdapter homeAdapter;
    private int nowPosition = -1;

    public int getNowPosition() {
        return nowPosition;
    }

    public void refreshNowPosition() {
        nowPosition = -1;
        homeAdapter.notifyDataSetChanged();
    }


    ArrayList<String> cafFiles = new ArrayList();
    ArrayList<String> cafJPG = new ArrayList();
    List<WaterMarkItemData> cacheList = new ArrayList<>();
    ArrayList<WaterMarkItemData> imageList = new ArrayList<>();

    public WaterMarkView(Context context) {
        super(context);
        mContext = context;
        this.init();
    }

    public WaterMarkView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        this.init();
    }

    public WaterMarkView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
        this.init();
    }

    private void init() {
        rootView = LayoutInflater.from(mContext).inflate(R.layout.view_water_mark, this);
        recyclerWatermark = rootView.findViewById(R.id.recycler_watermark);
        ivFinish = rootView.findViewById(R.id.iv_watermark_finish);
        initAdapter();
        rootView.setOnClickListener(v -> {
        });
        ivFinish.setOnClickListener(v -> {
            rootView.setVisibility(GONE);
            if (mItemClickListener != null) {
                mItemClickListener.onDismiss();
            }
        });
    }

    @SuppressLint("WrongConstant")
    private void initAdapter() {
        String extraCafDir = PathUtils.getWatermarkCafDirectoryDir();
        if (extraCafDir != null) {
            File extraCafDirFiles = new File(extraCafDir);
            List<String> fileNames = Arrays.asList(extraCafDirFiles.list());
            if (!fileNames.isEmpty()) {
                for (String fileName : fileNames) {
                    if (FileUtil.getExtensionName(fileName).equals("caf")) {
                        cafFiles.add(fileName);
                    } else if (FileUtil.getExtensionName(fileName).equals("jpg") || FileUtil.getExtensionName(fileName).equals("png")) {
                        cafJPG.add(fileName);
                    }
                }
            }
        }
        imageList.add(new WaterMarkItemData());
        imageList.add(new WaterMarkItemData(ASSETSPICTURE, type, "static_watermark.png", "static_watermark_item.png"));
        String cache = FileUtil.readWaterMarkCacheFile();
        if (cache != null) {
            try {
                Gson gson = new Gson();
                WaterMarkCacheData waterMarkCacheData = gson.fromJson(cache, WaterMarkCacheData.class);
                cacheList = waterMarkCacheData.getPicturePathName();
                imageList.addAll(cacheList);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
        linearLayoutManager.setOrientation(HORIZONTAL);
        recyclerWatermark.addItemDecoration(new SpaceItemDecoration(0, ScreenUtils.dip2px(mContext, 29)));
        recyclerWatermark.setLayoutManager(linearLayoutManager);//必须要加的
        homeAdapter = new HomeAdapter();
        recyclerWatermark.setAdapter(homeAdapter);
    }

    private boolean checkListContainString(List<String> list, String s) {
        for (String s1 : list) {
            if (s1.contains(s)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 从列表添加的都是静态水印类型
     * Added from the list are static watermark types
     */
    public void addDataAndRefresh(String picturePath) {
        if (!imageList.contains(new WaterMarkItemData(0, WaterMarkConstant.WATERMARKTYPE_STATIC, picturePath, picturePath))) {
            imageList.add(new WaterMarkItemData(SDCARDPICTURE, WaterMarkConstant.WATERMARKTYPE_STATIC, picturePath, picturePath));
            cacheList.add(new WaterMarkItemData(SDCARDPICTURE, WaterMarkConstant.WATERMARKTYPE_STATIC, picturePath, picturePath));
            nowPosition = imageList.size() - 1;
            homeAdapter.notifyDataSetChanged();
        }
    }

    class HomeAdapter extends RecyclerView.Adapter<HomeAdapter.MyViewHolder> {

        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {//布局绑定
            return new MyViewHolder(LayoutInflater.from(
                    mContext).inflate(R.layout.item_watermark_recycleview, parent,
                    false));
        }

        @Override
        public void onBindViewHolder(final MyViewHolder holder, @SuppressLint("RecyclerView") final int position) {//view获取和赋
            if (position == 0 && type == WaterMarkConstant.WATERMARKTYPE_STATIC) {
                Glide.with(mContext).load(R.mipmap.watermark_item_add).into(holder.imageView);
            } else {
                glideLoadPicture(imageList.get(position), holder.imageView);
            }
            holder.itemWatermarkCover.setVisibility(position == 0 ? View.INVISIBLE : nowPosition == position ? View.VISIBLE : View.INVISIBLE);
            holder.imageView.setOnClickListener(v -> {
                if (type == WaterMarkConstant.WATERMARKTYPE_STATIC && position == 0) {
                    //do nothing
                } else {
                    homeAdapter.notifyItemChanged(nowPosition);
                    nowPosition = position;
                    homeAdapter.notifyItemChanged(position);
                }
                String picturePath = imageList.get(position).getItemPicturePath();
                String waterMarkPicturePath = imageList.get(position).getWaterMarkpath();
                if (imageList.get(position).getItemPictureType() == ASSETSPICTURE) {
                    picturePath = "assets:/watermark/" + imageList.get(position).getItemPicturePath();
                    if (type == WaterMarkConstant.WATERMARKTYPE_STATIC) {
                        waterMarkPicturePath = "assets:/watermark/" + imageList.get(position).getWaterMarkpath();
                    }
                }
                if (mItemClickListener != null) {
                    mItemClickListener.onItemClick(position, imageList.get(position).getItemPictureType(), picturePath, type, waterMarkPicturePath);
                }
            });
        }

        private void glideLoadPicture(WaterMarkItemData waterMarkItemData, ImageView view) {
            if (waterMarkItemData.getItemPictureType() == SDCARDPICTURE) {
                if (waterMarkItemData.getItemPicturePath().length() == 0) {
                    Glide.with(mContext).load(R.mipmap.default_dynamic_picture).into(view);
                } else {
                    Glide.with(mContext).load(waterMarkItemData.getItemPicturePath()).into(view);
                }
            } else {
                Glide.with(mContext).load("file:///android_asset/watermark/" + waterMarkItemData.getItemPicturePath()).into(view);
            }
        }

        @Override
        public int getItemCount() {
            return imageList.size();
        }

        class MyViewHolder extends RecyclerView.ViewHolder {
            ImageView imageView;
            ImageView itemWatermarkCover;

            MyViewHolder(View view) {
                super(view);
                imageView = (ImageView) view.findViewById(R.id.item_watermark_image);
                itemWatermarkCover = (ImageView) view.findViewById(R.id.item_watermark_cover);
            }
        }
    }

    private OnWaterMarkItemClickListener mItemClickListener;

    public void setItemClickListener(OnWaterMarkItemClickListener mItemClickListener) {
        this.mItemClickListener = mItemClickListener;
    }

    public interface OnWaterMarkItemClickListener {
        void onItemClick(int position, int pictureType, String picturePath, int waterMarkType, String waterMarkPicture);

        void onDismiss();
    }

}
